package io.renren.modules.onstageLogin.controller;

import io.renren.common.annotation.LogOperation;
import io.renren.common.exception.ErrorCode;
import io.renren.common.exception.RenException;
import io.renren.common.utils.IpUtils;
import io.renren.common.utils.Result;
import io.renren.common.validator.ValidatorUtils;
import io.renren.common.validator.group.AddGroup;
import io.renren.common.validator.group.DefaultGroup;
import io.renren.modules.log.entity.SysLogLoginEntity;
import io.renren.modules.log.enums.LoginOperationEnum;
import io.renren.modules.log.enums.LoginStatusEnum;
import io.renren.modules.log.service.SysLogLoginService;
import io.renren.modules.onstageLogin.dto.OnStageLoginDTO;
import io.renren.modules.security.password.PasswordUtils;
import io.renren.modules.security.service.SysUserTokenService;
import io.renren.modules.sys.dto.SysRoleDTO;
import io.renren.modules.sys.dto.SysUserDTO;
import io.renren.modules.sys.enums.UserStatusEnum;
import io.renren.modules.sys.service.SysRoleService;
import io.renren.modules.sys.service.SysRoleUserService;
import io.renren.modules.sys.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 前台登录
 *
 * @author Mark sunlightcs@gmail.com
 */
@RestController
@RequestMapping("/onstage")
@Api(tags="前台登录管理")
public class OnStageLoginController {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysUserTokenService sysUserTokenService;
    @Autowired
    private SysLogLoginService sysLogLoginService;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysRoleUserService sysRoleUserService;

    private static final String WECHAT_ROLE = "WECHAT";



    @PostMapping("login")
    @ApiOperation(value = "登录")
    public Result login(HttpServletRequest request, @RequestBody OnStageLoginDTO login) {
        //效验数据
        ValidatorUtils.validateEntity(login);
        // 查询角色
        SysRoleDTO role = sysRoleService.getRole(WECHAT_ROLE);

        //用户信息
        SysUserDTO user = sysUserService.getByUsername(login.getUsername());
        if (user == null) {
            throw new RenException("该账号不存在，请注册后使用！");
        }

        List<Long> roleIdList = sysRoleUserService.getRoleIdList(user.getId());
        if (CollectionUtils.isEmpty(roleIdList) || !roleIdList.contains(role.getId())) {
            throw new RenException("该账号不存在，请注册后使用！");
        }

        SysLogLoginEntity log = new SysLogLoginEntity();
        log.setOperation(LoginOperationEnum.LOGIN.value());
        log.setCreateDate(new Date());
        log.setIp(IpUtils.getIpAddr(request));
        log.setUserAgent(request.getHeader(HttpHeaders.USER_AGENT));

        //用户不存在
        if(user == null){
            log.setStatus(LoginStatusEnum.FAIL.value());
            log.setCreatorName(login.getUsername());
            sysLogLoginService.save(log);

            throw new RenException(ErrorCode.ACCOUNT_PASSWORD_ERROR);
        }

        //密码错误
        if(!PasswordUtils.matches(login.getPassword(), user.getPassword())){
            log.setStatus(LoginStatusEnum.FAIL.value());
            log.setCreator(user.getId());
            log.setCreatorName(user.getUsername());
            sysLogLoginService.save(log);

            throw new RenException(ErrorCode.ACCOUNT_PASSWORD_ERROR);
        }

        //账号停用
        if(user.getStatus() == UserStatusEnum.DISABLE.value()){
            log.setStatus(LoginStatusEnum.LOCK.value());
            log.setCreator(user.getId());
            log.setCreatorName(user.getUsername());
            sysLogLoginService.save(log);

            throw new RenException(ErrorCode.ACCOUNT_DISABLE);
        }

        //登录成功
        log.setStatus(LoginStatusEnum.SUCCESS.value());
        log.setCreator(user.getId());
        log.setCreatorName(user.getUsername());
        sysLogLoginService.save(log);
        return sysUserTokenService.createToken(user.getId());
    }

    @PostMapping("register")
    @ApiOperation("注册")
    public Result register(@RequestBody OnStageLoginDTO dto){
        // 查询角色
        SysRoleDTO role = sysRoleService.getRole(WECHAT_ROLE);
        List<Long> roleIdList = new ArrayList<>();
        roleIdList.add(role.getId());
        // 保存账号
        SysUserDTO sysUserUserDTO = new SysUserDTO();
        sysUserUserDTO.setUsername(dto.getUsername());
        sysUserUserDTO.setPassword(dto.getPassword());
        sysUserUserDTO.setEmail(dto.getEmail());
        sysUserUserDTO.setMobile(dto.getMobile());
        sysUserUserDTO.setRealName(dto.getRealName());
        sysUserUserDTO.setRoleIdList(roleIdList);
        sysUserUserDTO.setStatus(1);
        sysUserService.save(sysUserUserDTO);
        return new Result();
    }

}
